/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { PureComponent, Fragment } from 'react';
import { Table, Alert, Button } from 'antd';
import DragTable from '@/components/DragTable';
import styles from './index.less';

function initTotalList(columns) {
  const totalList = [];
  columns.forEach(column => {
    if (column.needTotal) {
      totalList.push({ ...column, total: 0 });
    }
  });
  return totalList;
}

class StandardTable extends PureComponent {
  constructor(props) {
    super(props);
    const { columns } = props;
    const needTotalList = initTotalList(columns);

    this.state = {
      selectedRowKeys: props.defaultSelectedRowKeys || [],
      needTotalList,
    };
  }

  componentWillReceiveProps(nextProps) {
    // console.info("nextProps", nextProps.defaultSelectedRowKeys);
    // clean state
    if (!nextProps.selectedRows || nextProps.selectedRows.length === 0) {
      const needTotalList = initTotalList(nextProps.columns);
      this.setState({
        selectedRowKeys: [],
        needTotalList,
      });
    }
    // if (nextProps.defaultSelectedRowKeys) {
    //   this.setState({
    //     selectedRowKeys: nextProps.defaultSelectedRowKeys,
    //   });
    // }
  }

  handleRowSelectChange = (selectedRowKeys, selectedRows) => {
    const that = this;
    const { needTotalList: list } = this.state;
    const { onSelectRow, onSelectRowChange } = this.props;
    let needTotalList = [...list];
    needTotalList = needTotalList.map(item => ({
      ...item,
      total: selectedRows.reduce((sum, val) => sum + parseFloat(val[item.dataIndex], 10), 0),
    }));
    if (onSelectRow) {
      onSelectRow(selectedRows);
    }
    if (onSelectRowChange) {
      onSelectRowChange(selectedRowKeys, selectedRows, (key, rows) => {
        that.setState({ selectedRowKeys: key, needTotalList, selectedRows: rows });
      });
    } else {
      that.setState({ selectedRowKeys, needTotalList, selectedRows });
    }
  };

  handleTableChange = (pagination, filters, sorter) => {
    const { onChange } = this.props;
    if (onChange) {
      onChange(pagination, filters, sorter);
    }
  };

  patchRowKeysHandle = () => {
    const { onSelectRowHandle } = this.props;
    const { selectedRows } = this.state;
    if (onSelectRowHandle) {
      onSelectRowHandle(selectedRows, () => {
        this.cleanSelectedKeys();
      });
    }
  };

  cleanSelectedKeys = () => {
    this.handleRowSelectChange([], []);
  };

  render() {
    const { selectedRowKeys, needTotalList } = this.state;
    const {
      selectedRows,
      data: { list, pagination },
      loading,
      columns,
      rowKey,
      footer,
      onChange,
      rowSelection,
      ...rest
    } = this.props;
    const pageType = pagination ? pagination.sizeType !== false : true; // 兼容能否选择条目数
    const paginationProps = pagination
      ? {
          showSizeChanger: pageType,
          showQuickJumper: true,
          ...pagination,
          ...{ current: pagination.current * 1 }, // number类型
          ...{ total: pagination.total * 1 },
        }
      : false;
    // eslint-disable-next-line max-len
    // 内置onChange方法外部使用onSelectRow监听选择命中项,内置 selectedRowKeys逻辑，内置getCheckboxProps方法，合并props.rowSelection参数
    const newRowSelection = Object.assign(rowSelection || {}, {
      selectedRowKeys,
      onChange: this.handleRowSelectChange,
      getCheckboxProps: record => ({
        disabled: record.disabled,
      }),
    });

    return (
      <div className={styles.standardTable}>
        {selectedRows && (
          <div className={styles.tableAlert}>
            <Alert
              message={
                <Fragment>
                  已选择 <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a> 项&nbsp;&nbsp;
                  {needTotalList.map(item => (
                    <span style={{ marginLeft: 8 }} key={item.dataIndex}>
                      {item.title}
                      总计&nbsp;
                      <span style={{ fontWeight: 600 }}>
                        {item.render ? item.render(item.total) : item.total}
                      </span>
                    </span>
                  ))}
                  <a onClick={this.cleanSelectedKeys} style={{ marginLeft: 24 }}>
                    清空
                  </a>
                </Fragment>
              }
              type="info"
              showIcon
            />
          </div>
        )}
        <DragTable>
          <Table
            scroll={{ x: 1200 }}
            {...rest}
            loading={loading}
            rowKey={rowKey || 'key'}
            rowSelection={selectedRows && newRowSelection}
            dataSource={list}
            columns={columns}
            pagination={paginationProps}
            onChange={this.handleTableChange}
            footer={
              selectedRowKeys.length > 0 && footer && footer.name
                ? () => {
                    const Footer = footer.component;
                    return Footer ? (
                      <Footer selectedRows={this.state.selectedRows} />
                    ) : (
                      <Button
                        type="primary"
                        onClick={this.patchRowKeysHandle}
                        loading={footer.loading}
                      >
                        {footer.name}
                      </Button>
                    );
                  }
                : null
            }
          />
        </DragTable>
      </div>
    );
  }
}

export default StandardTable;
